package com.bmslz.monitor.helper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;

@Component
public class EmailHelper {

    @Value("${spring.mail.properties.from}")
    private String sendFrom;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送简单文本邮件
     *
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendFrom);  // 发件人（需与配置一致）
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    /**
     * 发送HTML格式邮件（支持超链接、样式等）
     */
    public void sendHtmlMail(String to, String subject, String htmlContent) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sendFrom);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);  // true表示发送HTML
            mailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    public void sendTemplateMail(String to, String subject, String title, String content, String event) {
        Context context = new Context();
        context.setVariable("alarmTime", LocalDateTime.now());
        context.setVariable("title", title);
        context.setVariable("content", content);
        context.setVariable("event", event);

        String htmlContent = templateEngine.process("email-alarm", context);
        sendHtmlMail(to, subject, htmlContent);
    }
}
